package com.xiaochen.manager.service.impl;

import com.xiaochen.common.exception.XiaoChenException;
import com.xiaochen.manager.mapper.SysMenuMapper;
import com.xiaochen.manager.service.SysMenuService;
import com.xiaochen.manager.utils.MenuHelper;
import com.xiaochen.model.entity.system.SysMenu;
import com.xiaochen.model.vo.common.ResultCodeEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.List;

@Service
public class SysMenuServiceImpl implements SysMenuService {

    @Autowired
    private SysMenuMapper sysMenuMapper;

    /**
     * 获取所有菜单
     * @return
     */
    @Override
    public List<SysMenu> findNodes() {
        // 1.查询所有的菜单
        List<SysMenu> sysMenuList = sysMenuMapper.findNodes();
        if (CollectionUtils.isEmpty(sysMenuList)){
            return null;
        }
        // 2.调用工具类的方法,把返回的菜单进行组装成要求的数据格式
        List<SysMenu> treeList = MenuHelper.buildTree(sysMenuList);

        return treeList;
    }

    /**
     * 添加菜单
     * @param sysMenu
     */
    @Override
    public void addSysMenu(SysMenu sysMenu) {
        sysMenuMapper.addSysMenu(sysMenu);
    }

    /**
     * 修改菜单
     * @param sysMenu
     */
    @Override
    public void updateSysMenu(SysMenu sysMenu) {
       sysMenuMapper.updateSysMenu(sysMenu);
    }

    /**
     * 删除菜单
     * @param id
     *
     * 注意:如果是简单的删除最下层的子菜单,允许直接删除,
     *      但是,如果要删除父菜单,需要判断他的下面是否还有子菜单,如果有子菜单,不允许删除
     *      没有子菜单,才允许删除
     */
    @Transactional
    @Override
    public void removeById(Long id) {
        // 1.判断当前菜单下面是否有子菜单,如果有子菜单,不允许删除
       int count = sysMenuMapper.selectCountById(id);
       if (count > 0){
           throw new XiaoChenException(ResultCodeEnum.NODE_ERROR);
       }
       sysMenuMapper.removeById(id);
    }

    /**
     * 根据id查询菜单
     * @param id
     * @return
     */
    @Override
    public SysMenu findById(Long id) {
        return sysMenuMapper.findById(id);
    }
}
